package com.example.goodpet.activity;

import static android.service.controls.ControlsProviderService.TAG;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.goodpet.R;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.DeviceUtil;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class PetFoodActivity extends FragmentActivity {

    private TextView title;
    private ImageView back;
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pet_food);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();
        ActivityManager.getInstance().addActivity(this);

        initView();
        methodRequiresTwoPermission();
        initListener();
    }

    private void initListener() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    //动态申请权限
    @AfterPermissionGranted(0)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.INTERNET};

        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            // ...
            initWebView();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.location_rationale),
                    0, perms);
            methodRequiresTwoPermission();
        }
    }

    private void initWebView() {
        String webUrl = getIntent().getStringExtra("webUrl");
//        String webUrl = "http://www.baidu.com";
        Log.e(TAG, "initWebView: "+webUrl );

        /**
         * setDownloadListener()是对加载的url是下载地址时的回调
         */
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

                // 上面的参数中，url对应文件下载地址，mimetype对应下载文件的MIME类型
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri uri = Uri.parse(url);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(uri);
                startActivity(intent);
            }
        });

        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                WebView.HitTestResult hit = view.getHitTestResult();
                //hit.getExtra()为null或者hit.getType() == 0都表示即将加载的URL会发生重定向，需要做拦截处理
                if (TextUtils.isEmpty(hit.getExtra()) || hit.getType() == 0) {
                    //通过判断开头协议就可解决大部分重定向问题了，有另外的需求可以在此判断下操作
                    Log.e("重定向", "重定向: " + hit.getType() + " && EXTRA（）" + hit.getExtra() + "------");
                    Log.e("重定向", "GetURL: " + view.getUrl() + "\n" + "getOriginalUrl()" + view.getOriginalUrl());
                    Log.d("重定向", "URL: " + url);
                }

                if (url.startsWith("http://") || url.startsWith("https://")) { //加载的url是http/https协议地址
                    view.loadUrl(url);
                    return false; //返回false表示此url默认由系统处理,url未加载完成，会继续往下走

                } else { //加载的url是自定义协议地址
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
            }

            @SuppressLint("WebViewClientOnReceivedSslError")
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                if (error.getPrimaryError() == android.net.http.SslError.SSL_INVALID){
                    handler.proceed();  // 接受信任所有网站的证书
                } else {
                    handler.cancel(); // 默认操作 不处理
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e(TAG, "onPageFinished: "+url );
            }
        });


        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//设置支持js
        settings.setSupportZoom(true); //支持缩放
        settings.setPluginState(WebSettings.PluginState.ON);//设置是否支持插件
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setDomStorageEnabled(true);

        //优先使用缓存
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        settings.setAllowFileAccess(true);

//        //设置支持本地存储
        settings.setDatabaseEnabled(true);
//        //设置缓存
        settings.setAppCacheEnabled(true);

        webView.loadUrl(webUrl);

    }



    private void initView() {
        back=findViewById(R.id.titlebar_common_back);
        title=findViewById(R.id.titlebar_common_title);
        webView=findViewById(R.id.webView);
        title.setText("宠物零食店铺");
    }
}